package traveldream.ejb.sessionBean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import traveldream.ejb.DTO.TransportationDTO;
import traveldream.ejb.entities.TransportationMean;
import traveldream.ejb.interfaces.NoDeleteException;
import traveldream.ejb.interfaces.NotFindException;
import traveldream.ejb.interfaces.TransportationBeanLocal;

/**
 * Session Bean implementation class TransportationBean
 */
@Stateless
public class TransportationBean implements TransportationBeanLocal {

	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public TransportationBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public List<TransportationDTO> getAllTransport() {
		// TODO Auto-generated method stub
		List<TransportationMean> t=em.createNamedQuery(TransportationMean.FIND_ALL).getResultList();
		List<TransportationDTO> tDTO = new ArrayList<TransportationDTO>();
		for(int i=0;i<t.size();i++)
		{
			tDTO.add(t.get(i).convertToDTO());
		}
		return tDTO;
	}
	
	

	@Override
	public TransportationDTO find(int id) throws NotFindException {
		try{
		return em.find(TransportationMean.class,id).convertToDTO();
		}
		catch(NullPointerException e){
			throw new NotFindException();
		}
	}

	@Override
	public void delete(int id) throws NotFindException,NoDeleteException{
		// TODO Auto-generated method stub
		try{
		TransportationMean t=em.find(TransportationMean.class,id);
		for(int i=0;i<t.getDefaultPackagesArrival().size();i++){
			if(!t.getDefaultPackagesArrival().get(i).isInvalid())
				throw new NoDeleteException();				
		}
		for(int i=0;i<t.getDefaultPackagesDepature().size();i++){
			if(!t.getDefaultPackagesDepature().get(i).isInvalid())
				throw new NoDeleteException();
		}
			t.setInvalid(true);
			}
			catch(NullPointerException e){
				throw new NotFindException();
			}
	}

}
